﻿using System;
using Quartz;
using System.Threading.Tasks;
using System.Threading;

namespace AVCJobDispatcherLinux.TaskJobEngine
{
    public class Worker
    {
        private static async Task<DateTimeOffset> ExecuteAsync(IJobDetail jobDetail, ITrigger trigger, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (await SchedulerSingleton.SchedulerFactory.CheckExists(jobDetail.Key, cancellationToken))
            {
                await SchedulerSingleton.SchedulerFactory.DeleteJob(jobDetail.Key, cancellationToken);
            }

            return await SchedulerSingleton.SchedulerFactory.ScheduleJob(jobDetail, trigger, cancellationToken);
        }

        public static async Task<DateTimeOffset> ExecuteAsync(JobInfo entity, Type jobType)
        {
            TaskJobManager.AddJobInfo(entity);
            return await ExecuteAsync(
                Tasks.BuilderWithType(JobTriggerConver.GetJobKey(entity.Name, entity.GroupName), jobType, entity.Id), 
                Trigger.Builder(JobTriggerConver.GetTriggerKey(entity.Name, entity.GroupName), entity));
        }

        public static async Task<DateTimeOffset> ExecuteGivenTimesAsync<TaskJob>(JobInfo entity, int times) where TaskJob : IJob
        {
            TaskJobManager.AddJobInfo(entity);
            return await ExecuteAsync(
                Tasks.Builder<TaskJob>(JobTriggerConver.GetJobKey(entity), entity.Id),
                Trigger.BuilderRepeatCount(JobTriggerConver.GetTriggerKey(entity), entity.Second, times));
        }

        public static async Task<DateTimeOffset> ExecuteAsync<TaskJob>(JobInfo entity) where TaskJob : IJob
        {
            TaskJobManager.AddJobInfo(entity);
            return await ExecuteAsync(
                Tasks.Builder<TaskJob>(JobTriggerConver.GetJobKey(entity), entity.Id), 
                Trigger.Builder(JobTriggerConver.GetTriggerKey(entity), entity));
        }

        public static async Task<bool> StopAsync(JobInfo entity)
        {
            var triggerKey = JobTriggerConver.GetTriggerKey(entity);
            await SchedulerSingleton.SchedulerFactory.PauseTrigger(triggerKey);
            bool tjob = await SchedulerSingleton.SchedulerFactory.UnscheduleJob(triggerKey);
            await SchedulerSingleton.SchedulerFactory.DeleteJob(JobTriggerConver.GetJobKey(entity));
            return true;
        }

        public static async Task<DateTimeOffset> ExecuteFixedJobAsync<TaskJob>(JobInfo entity) where TaskJob : IJob
        {
            return await ExecuteAsync(
                Tasks.Builder<TaskJob>(JobTriggerConver.GetJobKey(entity), entity.Id),
                Trigger.Builder(JobTriggerConver.GetTriggerKey(entity), entity));
        }
    }
}
